package com.example.administrator.szb.util;

import android.util.Base64;

import com.qiniu.android.utils.UrlSafeBase64;

import org.json.JSONObject;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author pdf
 */
public class TokenUtil {
    private static final String MAC_NAME = "HmacSHA1";
    private static String ak =  "ZJ_NhcokmzYjnjUdksQv83-ngnuHEZuyr8k3VgOG";
    private static String sk = "qH_XszYsZUmbODl_NjEzXDgs6AnFEcYP5CGk68BS";
    private static String scope = "shizhibao";
    public static String endcoding(String json_string,String isType,String key){
        key = md5(key);
        int key_length = key.length();
        // $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        String decodedString =new String(Base64.decode(json_string.getBytes(), Base64.DEFAULT));
        String encodeString = null;
        encodeString = md5(json_string+key).substring(0,8)+json_string;
        json_string = isType.equals("D")? decodedString:encodeString;
        int json_string_length = json_string.length();

        int[] rndkey = new int[256];
        int[] box = new int[256];

        String result = "";
        for(int i=0;i<=255;i++){

            rndkey[i]=(int)(key.toCharArray()[i%key_length]);

            box[i]=i;

        }
        for(int j=0,i=0;i<256;i++){

            j=(j+box[i]+rndkey[i])%256;

            int tmp=box[i];

            box[i]=box[j];

            box[j]=tmp;

        }

        for(int a=0,j=0,i=0;i<json_string_length;i++){

            a=(a+1)%256;

            j=(j+box[a])%256;

            int tmp=box[a];

            box[a]=box[j];

            box[j]=tmp;

            result +=((int)(json_string.toCharArray()[i])^(box[(box[a]+box[j])%256]));

        }

        result = md5(result);

        if("D".equals(isType)){

            String str = null;
            str = md5(result.substring(8,result.length())+key).substring(0,8);

            md5(result.substring(0,8)+key).substring(0,8);
            if(result.substring(0,8).equals(str)){

                return result.substring(8,result.length());

            }else{

                return "";

            }

        }else{

            return result.replace('=',' ').trim();

        }
    }

    public static String md5(String input) {
        String result = input;
        if(input != null) {
            MessageDigest md = null; //or "SHA-1"
            try {
                md = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            md.update(input.getBytes());
            BigInteger hash = new BigInteger(1, md.digest());
            result = hash.toString(16);
            while(result.length() < 32) { //31位string
                result = "0" + result;
            }
        }
        return result;
    }

    public static String getToken(){
        try{
            JSONObject _json = new JSONObject();
            long _dataline = System.currentTimeMillis() / 1000 + 3600;
            _json.put("deadline", _dataline);// 有效时间为一个小时
            _json.put("scope", scope);
            String _encodedPutPolicy = UrlSafeBase64.encodeToString(_json.toString().getBytes());
            byte[] _sign = HmacSHA1Encrypt(_encodedPutPolicy, sk);
            String _encodedSign = UrlSafeBase64.encodeToString(_sign);
            return ak + ':' + _encodedSign + ':'
                    + _encodedPutPolicy;
        }catch (Exception e){
            e.toString();
        }
        return null;
    }

    /**
     *
     使用 HMAC-SHA1 签名方法对encryptText进行签名
     *
     * @param encryptText
     *            被签名的字符串
     * @param encryptKey
     *            密钥
     * @return
     * @throws Exception
     */
    public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey)
            throws Exception {
        byte[] data = encryptKey.getBytes("UTF-8");
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        // 生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(MAC_NAME);
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);
        byte[] text = encryptText.getBytes("UTF-8");
        // 完成 Mac 操作
        return mac.doFinal(text);
    }
}
